package com.bilibili.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bilibili.entity.User;
import com.bilibili.entity.WatchHistory;
import com.bilibili.service.WatchHisoryService;
import com.bilibili.service.impl.WatchHisoryServiceImpl;

@SuppressWarnings("serial")
@WebServlet("/addHistory.do")
public class AddHistoryServlet extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String videoId = request.getParameter("videoId");
		int video_id = -1;
		try {
			video_id = Integer.parseInt(videoId);
		} catch (Exception e) {
			// TODO: handle exception
		}
		if(((User)request.getSession().getAttribute("loginUser")) != null) {
			int user_id = ((User)request.getSession().getAttribute("loginUser")).getUserId();
			WatchHistory wh = new WatchHistory();
			wh.setUserId(user_id);
			wh.setVideoId(video_id);
			WatchHisoryService whs = new WatchHisoryServiceImpl();
			WatchHistory w = whs.selectWatchHistory(wh);
			if(w != null) {
				if(whs.deleteWatchHistory(w.getHistoryId())) {
					whs.insertWatchHistory(wh);
				}
			}else {
				whs.insertWatchHistory(wh);
			}
		}
	}
}
